/**
 * Created by lenovo on 2017/5/15.
 */
const DBPool = require('../dao/DBConnectPool');
const async = require('async');
const WXMember = require('./WXMemberController');
const emojiRegex = require('emoji-regex');

function timeToStr(time) {
    var date = new Date(time);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = date.getDate() + ' ';
    var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
    var s = date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds();

    return Y+M+D+h+m+s;
}

module.exports = {
    getCinemaRoomTypes: function (req, res) {
        var cinemaCode = req.body.cinemacode;
        if (!cinemaCode) {
            res.json({
                errorMessage:'参数错误'
            });
            return;
        }

        DBPool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                res.json({
                    errorMessage:'数据库链接错误'
                });
                connection.release();
                return;
            }

            async.waterfall([
                /**
                 * 查询相关影吧
                 */
                    function (callback) {
                    //查询相关影吧
                    var sql = 'select app_booking_start,app_booking_end,booking_start_timezone,booking_add_timezone '
                        + ' from app_cinema'
                        + ' where cinema_code = ? ';

                    connection.query(sql, [cinemaCode], function (queryErr, rows) {
                        if (queryErr) {
                            callback('数据库链接错误');
                        } else {
                            callback(null, {rows: rows})
                        }
                    });
                },
                /**
                 * 获取可预约点播影院影厅种类
                 */
                    function (arg1, callback) {
                    //该影吧不存在
                    if (arg1.rows.length == 0) {
                        callback('数据库链接错误');
                    } else {
                        //获取可预约点播影院影厅种类
                        var sql = " SELECT DISTINCT a.* FROM app_cinema_roomtype AS a " +
                            " INNER JOIN app_cinema AS b ON a.cinema_id = b.cinema_id" +
                            " INNER JOIN app_cinema_room AS c ON a.roomtype_id = c.roomtype_id" +
                            " WHERE a.roomtype_status = 1 AND a.online_booking_flag = 1" +
                            " AND c.room_status = 1 AND c.online_booking_flag = 1" +
                            " AND b.cinema_status = 1 AND b.online_booking_flag = 1 " +
                            " AND b.cinema_code = ?" +
                            " ORDER BY a.roomtype_price ASC ";

                        connection.query(sql, [cinemaCode], function (queryErr, rows) {
                            if (queryErr) {
                                callback('数据库链接错误');
                            } else {
                                callback(null, {cinema_info:arg1.rows[0],roomtype_list:rows})
                            }
                        });
                    }

                }
            ], function (err, result) {

                if (err) {
                    res.json({
                        errorMessage:'数据库链接错误'
                    });
                    connection.release();
                    return;
                }

                res.json({
                    rows : result,
                });
                connection.release();
            });
        });

    },
    showCinemaRoomType :function (req, res) {
        let phoneNumber = null;
        WXMember.checkPhoneNumber(req,res,function (err, code, result) {
            if (result){
                phoneNumber = result.phone_number;
            }

            var roomTypeId = req.query.roomtype_id;
            var errorCode = 0;
            var errorMessage = '';
            if (!roomTypeId) {
                errorCode = 101;
                errorMessage = '参数错误';
                res.render('cinemaroomtype', {
                    title: '房间类型',
                    data: {
                        status: 'error',
                        errorCode: errorCode,
                        errorMessage: errorMessage,
                    }
                });
                return;
            }

            DBPool.getPoolConnection('mtsc', function (err, connection) {
                if (err) {
                    errorCode = 102;
                    errorMessage = '数据库链接错误';
                    res.render('cinemaroomtype', {
                        title: '房间类型',
                        data: {
                            status: 'error',
                            errorCode: errorCode,
                            errorMessage: errorMessage,
                        }
                    });
                    connection.release();
                    return;
                }

                var sql = " SELECT a.* ,b.cinema_code, b.app_booking_start,b.app_booking_end,b.booking_start_timezone,b.booking_add_timezone" +
                    " FROM app_cinema_roomtype AS a " +
                    " INNER JOIN app_cinema AS b ON a.cinema_id = b.cinema_id" +
                    " WHERE a.roomtype_id = ?";

                connection.query(sql, [roomTypeId], function (queryErr, rows) {
                    if (queryErr) {
                        errorCode = 102;
                        errorMessage = '数据库链接错误';
                        res.render('cinemaroomtype', {
                            title: '房间类型',
                            data: {
                                status: 'error',
                                errorCode: errorCode,
                                errorMessage: errorMessage,
                            }
                        });
                        connection.release();
                        return;
                    }

                    console.log(rows[0]);

                    var array = [];
                    var weekStr = ['周日','周一','周二','周三','周四','周五','周六'];
                    var today = new Date();
                    for (var i = 0;i<7;i++){
                        var tmp = new Date(today.getTime() + 24*60*60*1000*i);

                        var year = tmp.getFullYear();
                        var month = tmp.getMonth() + 1;
                        var date = tmp.getDate();
                        var week = tmp.getDay();

                        if (month<10){
                            month = '0'+ month;
                        }
                        if (date<10){
                            date = '0'+ date;
                        }
                        array[i] = {
                            year:year,
                            date:month + '-' + date,
                            week:weekStr[week]
                        }
                    }
                    console.log(array);
                    rows[0].dates = array;
                    res.render('cinemaroomtype', {
                        title: '房间类型',
                        data: {
                            status: 'success',
                            rows : rows[0],
                            phoneNumber: phoneNumber
                        }
                    });

                    connection.release();
                });
            });

        });

    },
    submitBooking:function (req, res) {

        if (!req.signedCookies.userinfo || !req.signedCookies.userinfo.openid) {
            res.json({
                errorMessage:'没有openid',
            });
            return;
        }
        var openId = req.signedCookies.userinfo.openid;

        var para = req.body;
        var cinemaCode = para.cinemaCode;
        var roomTypeId = para.roomtypeId;
        var bookingDate = para.bookingDate;//日期
        var startTime = para.startTime;//开始时间

        var watchingMinutes = para.watchingMinutes;//时长
        var bookingCode = para.bookingCode;//联系电话
        //var numbers = para.numbers;//人数
        var bookingContact = para.bookingContact;//联系人
        var userComment = para.userComment;//用户留言

                //计算预约时段（当日零点的时间戳）
        var zeroStr = bookingDate + ' ' + '00:00:00';
        var zeroStamp = Date.parse(zeroStr);
        //观影时长(秒)
        var timezone = watchingMinutes * 60 *1000;

        //开始时间为当天的0点加上所选时间
        var startStamp = zeroStamp + parseInt(startTime.split(':')[0])*60*60*1000 + parseInt(startTime.split(':')[1])*60*1000;
        var startStr = timeToStr(startStamp);
        //开始时间加上所选时长
        var endStamp = startStamp + timezone;
        var endStr = timeToStr(endStamp);
        //当前时间戳
        var nowStamp = Date.parse(new Date());


        var startminute = parseInt(startStamp /1000 / 60);
        var endminute = parseInt(endStamp /1000 / 60);
        var nowminute = parseInt(Date.parse(new Date()) /1000 / 60);


        const regex = emojiRegex();
        let match;
        while (match = regex.exec(userComment)) {
            res.json({
                errorCode: 103,
                errorMessage:'禁止输入表情符号！'
            });
            return;
        }

        DBPool.getPoolConnection('mtsc', function (err, connection) {
            var errorCode = 0;
            var errorMessage = '';
            if (err) {
                errorCode = 102;
                errorMessage = '数据库链接错误';
                res.json({
                    errorCode:errorCode,
                    errorMessage:errorMessage
                });
                return;
            }

            async.waterfall([
                //查询相关影吧
                function (callback) {
                    var sql = 'select cinema_id,app_booking_start,app_booking_end,booking_start_timezone,booking_add_timezone '
                        + ' from app_cinema'
                        + ' where cinema_code = ? ';

                    connection.query(sql, [cinemaCode], function (queryErr, rows) {
                        if (queryErr) {
                            callback('数据库链接错误!');
                        } else {
                            callback(null, {rows: rows})
                        }
                    });
                },

                function (arg1, callback) {
                    //该影吧不存在
                    if (arg1.rows.length == 0) {
                        callback('该影吧不存在!');
                    } else {
                        var cinemaId = arg1.rows[0].cinema_id;

                        //每日订单不得多于3单
                        var sql = 'select a.booking_id ' +
                            ' FROM app_cinema_booking as a' +
                            ' INNER JOIN app_cinema_room AS b ON a.room_id = b.room_id ' +
                            ' INNER JOIN app_cinema_roomtype AS c ON c.roomtype_id = b.roomtype_id' +
                            ' INNER JOIN app_cinema AS d ON d.cinema_id = c.cinema_id' +
                            ' WHERE d.cinema_id = ? ' +
                            ' AND a.booking_status = 0 ' +
                            ' AND a.open_id = ? ' +
                            ' AND a.start_time LIKE ? ';

                        connection.query(sql, [cinemaId,openId,'%'+ bookingDate +' %'], function (queryErr, rows) {
                            if (queryErr) {
                                callback('数据库链接错误!');
                            } else {
                                callback(null, arg1,{rows: rows})
                            }
                        });

                    }
                },
                function (arg1,arg2, callback) {

                    if (arg2.rows.length >= 3) {
                        callback('每日订单不得多于3单!');
                    } else {

                        var cinemaId = arg1.rows[0].cinema_id;
                        //开始时间必须为当前时间3小时后
                        if ((startStamp - nowStamp) < 3*60*60*1000) {
                            callback('只能预约三小时以后的场次！');
                        } else {
                        //
                        // if (startminute - nowminute < 180) {
                        //     callback('只能预约三小时以后的场次！');
                        // } else {

                            var sql = "SELECT count(*) AS closeflag " +
                                " FROM app_cinema_close " +
                                " WHERE cinema_id = ? " +
                                " AND close_start <= ? " +
                                " AND close_end >= ? ";

                            connection.query(sql, [cinemaId,bookingDate+ '00:00:00',bookingDate+ '00:00:00'], function (queryErr, rows) {
                                if (queryErr) {
                                    callback('数据库链接错误!');
                                } else {
                                    callback(null,arg1,arg2, {rows: rows})
                                }
                            });
                        }
                    }
                },
                function (arg1,arg2,arg3, callback) {
                    //检查当天是否歇业
                    if (arg3.rows[0].closeflag) {
                        callback( '本日歇业，不可预订！');
                    } else {
                        var cinema = arg1.rows[0];

                        //检查开始时间是否在营业时间之内
                        //营业开始时间
                        var cinemaStartStamp = zeroStamp + parseInt(cinema.app_booking_start.split(':')[0])*60*60*1000 + parseInt(cinema.app_booking_start.split(':')[1])*60*1000;
                        //营业结束时间
                        var m = parseInt(cinema.app_booking_end.split(':')[0]);
                        if (m <= 6){
                            m = m + 24
                        }
                        var cinemaEndStamp = zeroStamp + m*60*60*1000 + parseInt(cinema.app_booking_end.split(':')[1])*60*1000

                        if ( startStamp < cinemaStartStamp || startStamp > cinemaEndStamp ){
                            callback('预订开始时间在营业时间之外！');
                        }
                        else if ( endStamp < cinemaStartStamp || endStamp > cinemaEndStamp ){
                            callback('预订结束时间在营业时间之外！');
                        }
                        // if (cinema.app_booking_start > startTime || (e + ':'+ cinema.app_booking_end.split(':')[1])  <= startTime) {
                        //     callback('预订开始时间在营业时间之外！');
                        // }
                        //检查观影时长是否正常
                        else if ((endminute - startminute) < cinema.booking_start_timezone || (endminute - startminute) > 600) {
                            callback('观影时长过长或过短！');
                        }
                        //该时段影厅已经被预约一空！
                        else {
                            var sql = " SELECT d.room_id AS room_id, d.room_name AS room_name" +
                                " FROM (" +
                                " SELECT COUNT(c.booking_id) AS COUNT, b.room_id AS room_id, b.room_name AS room_name" +
                                " FROM app_cinema_roomtype AS a " +
                                " INNER JOIN app_cinema_room as b ON  a.roomtype_id = b.roomtype_id " +
                                " LEFT JOIN (" +
                                " SELECT *  FROM app_cinema_booking " +
                                " WHERE end_time >= ? AND start_time <= ? AND booking_status < 2" +
                                " ) AS c  on b.room_id = c.room_id" +
                                " WHERE a.roomtype_id = ? AND a.roomtype_status = 1 " +
                                " AND b.room_status = 1 AND b.online_booking_flag = 1" +
                                " GROUP BY b.room_id" +
                                " ) AS d " +
                                " WHERE d.COUNT = 0 LIMIT 1";

                            connection.query(sql, [startStr,endStr,roomTypeId], function (queryErr, rows) {
                                if (queryErr) {
                                    callback('数据库链接错误!');
                                } else {
                                    callback(null,arg1,arg2,arg3,{rows: rows})
                                }
                            });
                        }
                    }
                },
                function (arg1,arg2,arg3,arg4, callback) {
                    var room = null;
                    var roomlist = arg4.rows;
                    if (roomlist.length > 0) {
                        room = roomlist[0];
                    }

                    // var comment = JSON.stringify({
                    //     numbers:numbers,
                    //     bookingContact:bookingContact,
                    //     userComment:userComment
                    // });
                    var comment = '';
                    // if (numbers){
                    //     comment += numbers + '人';
                    // }
                    if (bookingContact){
                        comment += bookingContact;
                    }
                    if (userComment){
                        comment += ','+ userComment;
                    }
                    console.log('WXBookingController.js:'+comment);

                    if (!room){
                        callback('该时段影厅已经被预约一空!');
                    } else {
                        //影吧订单生成
                        var sql = ' INSERT INTO app_cinema_booking ' +
                            ' (booking_type, app_id, booking_code,room_id,booking_amount,start_time,end_time,' +
                            ' booking_date,user_comment,booking_status,pay_status,close_status,createtime,updatetime,open_id) ' +
                            ' VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ';
                        connection.query(sql, [0,0,bookingCode,room.room_id,0,startStr,endStr,
                            timeToStr(new Date()),
                            comment,0,0,0,
                            timeToStr(new Date()),
                            timeToStr(new Date()),
                            openId], function (queryErr, result) {
                            console.log('WXBookingController.js:'+sql);
                            console.log('WXBookingController.js:'+queryErr);
                            if (queryErr) {
                                callback('影厅预订失败!');
                            } else {
                                callback(null,arg1,arg2,arg3,arg4, {result: result})
                            }
                        });
                    }
                },
                function (arg1,arg2,arg3,arg4,arg5, callback) {
                    if (!arg5.result.insertId) {
                        callback('影厅预订失败!');
                    } else {
                        //订单支付编号生成
                        var ordercode = Date.parse(new Date())/1000;
                        var bookingid = arg5.result.insertId
                        if (bookingid < 10) {
                            ordercode += "000" + bookingid;
                        } else if (bookingid < 100) {
                            ordercode += "00" + bookingid;
                        } else if (bookingid < 1000) {
                            ordercode += "0" + bookingid;
                        } else if (bookingid >= 100000) {
                            ordercode += bookingid % 10000;
                        } else {
                            ordercode += bookingid;
                        }

                        var sql = ' UPDATE app_cinema_booking ' +
                            ' SET order_code = ? ' +
                            ' WHERE  booking_id = ? ';

                        connection.query(sql, ['T'+ordercode,bookingid], function (queryErr, result) {
                            if (queryErr) {
                                callback('数据库链接错误!');
                            } else {
                                callback(null,{
                                    result: result,
                                    bookingid : 'T'+ordercode
                                })
                            }
                        });
                    }

                }

            ],function (err, result) {
                if (err) {
                    res.json({
                        errorMessage:err
                    });
                }else {
                    res.json({
                        booking_id:result.bookingid
                    });
                }
                connection.release();
            })


        })



    },

    showBookingOrders: function (req, res) {
        res.render('bookingorders', {
            title: '我的订单',
        });

    },
    getBookingOrders: function (req, res) {

        if (!req.signedCookies.userinfo || !req.signedCookies.userinfo.openid) {
            res.json({
                errorMessage:'没有openid',
            });
            return;
        }
        var openId = req.signedCookies.userinfo.openid;

        var state = req.body.state;
        var page1 = req.body.page1;
        var page2 = req.body.page2;
        var page3 = req.body.page3;
        var limit = 10;

        DBPool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                res.json({
                    errorMessage: '数据库链接错误',
                });
                connection.release();
                return;
            }

            var sql = 'SELECT a.booking_id, a.order_code, a.booking_type, a.booking_status,' +
                ' a.pay_status, a.close_status, a.booking_amount, a.expire_flag,' +
                ' DATE_FORMAT(a.createtime , "%Y-%m-%d %H:%i") as createtime, ' +
                ' b.room_id, b.room_name, c.roomtype_id, c.roomtype_name, d.cinema_id, d.cinema_name, ' +
                ' a.user_comment , c.roomtype_pic, ' +
                ' DATE_FORMAT(a.start_time, "%m月%d日") AS booking_date, ' +
                ' DATE_FORMAT(a.start_time, "%H:%i") AS start_time, ' +
                ' DATE_FORMAT(a.end_time, "%H:%i") AS end_time, ' +
                ' DAYOFWEEK(a.start_time) AS week_day ' +
                ' FROM app_cinema_booking AS a ' +
                ' INNER JOIN app_cinema_room AS b ON a.room_id = b.room_id ' +
                ' INNER JOIN app_cinema_roomtype AS c ON b.roomtype_id = c.roomtype_id ' +
                ' INNER JOIN app_cinema AS d ON c.cinema_id = d.cinema_id ' +
                ' WHERE a.open_id =  ? ' +
                ' AND a.booking_type = 0 ' +
                ' AND a.hide_flag = 0 ';

            if (state == 1){
                sql += " AND a.booking_status = 0 ";
                sql += " ORDER BY a.booking_id DESC LIMIT " + page1*limit + "," +  limit ;
            } else if (state == 2) {
                sql += " AND a.booking_status = 1 ";
                sql += " ORDER BY a.booking_id DESC LIMIT " + page2*limit + "," +  limit ;
            } else {
                sql += " AND a.booking_status = 2 ";
                sql += " ORDER BY a.booking_id DESC LIMIT " + page3*limit + "," +  limit ;
            }

            connection.query(sql, [openId], function (queryErr, rows) {
                if (queryErr) {
                    res.json({
                        errorMessage: '数据库链接错误',
                    });
                    connection.release();
                    return;
                }

                var flg = 0;
                if (rows.length < limit) {
                    flg = 1;
                }

                res.json({
                    orders: rows,
                    isLast:flg
                });
                connection.release();
            });

        });

    },

    cancelBooking:function (req ,res) {
        var bookingId = req.body.bookingId;
        DBPool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                res.json({
                    errorMessage: '数据库链接错误'
                });
                connection.release();
                return;
            }

            var sql = 'UPDATE app_cinema_booking SET booking_status = 2 WHERE booking_id = ? ';
            connection.query(sql, [bookingId], function (queryErr, result) {
                if (queryErr) {
                    res.json({
                        errorMessage: '数据库链接错误',
                    });
                    connection.release();
                    return;
                }
                res.json({
                    result: result.changedRows
                });
                connection.release();
            });
        });
    }


};
